package com.nantian.nfcm.bms.report.web;

import com.nantian.nfcm.bms.loan.entity.LoanDetailedReport;
import com.nantian.nfcm.bms.report.service.LoanDetailedReportService;
import com.nantian.nfcm.bms.report.vo.LoanDetailedReportBean;
import com.nantian.nfcm.util.DataUtil;
import com.nantian.nfcm.util.DateUtil;
import com.nantian.nfcm.util.ServiceException;
import com.nantian.nfcm.util.service.ParamService;
import com.nantian.nfcm.util.vo.GridData;
import com.nantian.nfcm.util.vo.LoginBean;
import com.nantian.nfcm.util.vo.ResultInfo;
import org.apache.log4j.Logger;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

@Controller
@RequestMapping(("/report"))
public class LoanReportController extends ReportController {
    private static Logger log = Logger.getLogger(LoanReportController.class.getName());
    private ParamService paramService;
    private LoanDetailedReportService loanDetailedReportService;
    private static final int limit = 500;
    private static final String fileSavePath = "fileSavePath";
	private String excelPath = "";//指定到服务器某个文件路径

    @Autowired
    public LoanReportController(ParamService paramService, LoanDetailedReportService loanDetailedReportService) {
        this.paramService = paramService;
        this.loanDetailedReportService = loanDetailedReportService;
    }

    @RequestMapping("/loanReport")
    @ResponseBody
    public ResultInfo poiLoanReport(LoanDetailedReportBean loanDetailedReportBean, HttpServletRequest request) {
        ResultInfo resultInfo = new ResultInfo();
        try {
            String savePath = paramService.findParamById(fileSavePath).getParamValue();
            if (savePath == null || savePath.equals("")) {
                throw new ServiceException("参数[" + fileSavePath + "]错误");
            }
            if(!new File(savePath).exists()){
                new File(savePath).mkdirs();
            }
            String time = DateUtil.getCurrentTime("yyyyMMddHHmmss");
            String fileName = "loanReport" + time + ".xlsx";
            String path = savePath + File.separator + fileName;
            LoginBean loginBean = (LoginBean) request.getSession().getAttribute("loginInfo");
            String formatTime = DateUtil.getFormatTime(time);

            String title = "盘龙联社个人金融业务部贷款审批情况统计表";
            String[] headerNames = {"贷款编号", "借款人", "身份证号码", "上报时间", "营销人姓名", "营销人岗位",
                    "经办人姓名", "经办人岗位", "业务品种", "申贷金额（万元）", "申贷期限（月）", "担保情况",
                    "审批时间", "是否通过", "审批业务品种", "审批金额（万元）", "审批期限（月）", "审批利率",
                    "审批担保方式", "审批还款方式", "审查人", "是否续贷", "备注"};
            String[] headerColumns = {"loanId", "borrowerName", "credentialNo", "pickupTime", "marketer", "marketerPost",
                    "operator", "operatorPost", "businessType", "amount", "term", "guaranteeMethod",
                    "approvalTime", "loanResult", "apprBusinessType", "apprAmount", "apprTerm", "apprRate",
                    "apprGuaranteeMethod2", "repaymentMethod", "examineHandler", "isRenew", "remark"};
            String operater = "【操作人员】：" + loginBean.getRealName() + " 【时间】 : " + formatTime;
            getExcelFile(path,title,operater,headerNames,headerColumns,loanDetailedReportBean);
            resultInfo.setSuccess("true");
            resultInfo.setData(fileName);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return resultInfo;
    }

    /**
     * 通过数据库查询后导出excel报表
     *
     * @throws Exception
     */
    protected void getExcelFile(String filePath, String title, String operater,
                                String[] headerNames, String[] headerColumns,
                                LoanDetailedReportBean loanDetailedReportBean) {
        String sheetName = "exportData";
        int colCount = headerNames.length;
        Workbook workbook = null;
        Sheet sheet = null;
        FileOutputStream out = null;
        try {
            File file = new File(filePath);
            out = new FileOutputStream(file);
            workbook = new XSSFWorkbook();
            sheet = workbook.createSheet(sheetName);

            createTitle(workbook, sheet, title, 0, 0, 0, colCount);
            createOperater(workbook, sheet, operater, 1, 1, 0, colCount);
            createHeader(workbook, sheet, headerNames, 2, 1, 0);

            GridData<LoanDetailedReport> gridData = loanDetailedReportService.findByCondition(0, limit, loanDetailedReportBean);
            List<LoanDetailedReport> datas = gridData.getData();
            if (datas != null && datas.size() > 0) {
                int nextRow = wirteExcel(workbook, sheet, headerColumns, 3, 0, datas);

                int totalPage = gridData.getTotalPage();
                for (int i = 1; i < totalPage; i++) {
                    gridData = loanDetailedReportService.findByCondition(i, limit, loanDetailedReportBean);
                    datas = gridData.getData();
                    nextRow = wirteExcel(workbook, sheet, headerColumns, nextRow, 0, datas);
                }
            } else {
                createNull(workbook, sheet, 3, 3, 0, colCount);
            }
            workbook.write(out);
        } catch (FileNotFoundException e) {
            log.error(e.getMessage());
        } catch (IOException e) {
            log.error(e.getMessage());
        } catch (ServiceException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.flush();
                    out.close();
                } catch (IOException e) {
                    log.error(e.getMessage());
                }
            }
        }
    }
    
    @RequestMapping("/downloadExcel")
    // @ResponseBody
     public void downloadExcel(String fileName,HttpServletRequest request, HttpServletResponse response) throws Exception
 	{
 		String path = "";
 		String savePath = paramService.findParamById(fileSavePath).getParamValue();
 		if(excelPath.equals(""))
 		{
 			path = savePath+File.separator+fileName;
 		}
 		else
 		{
 			path = excelPath + fileName;
 		}
 		File file = new File(path);
 		downloadFile(file,request,response);
 		
 		DataUtil.deleteFileOrFolder(file);
 	}
    
    /**
     * 查询贷款明细报表信息
     * @param loanDetailedReportBean
     * @param request
     * @return
     */
    @RequestMapping("/findLoanInfosByCondition")
    @ResponseBody
    public ResultInfo findLoanInfosByCondition(HttpServletRequest request, int page, int size, LoanDetailedReportBean loanDetailedReportBean) {
        ResultInfo resultInfo = new ResultInfo();
        try {
        	GridData<LoanDetailedReport> gd = loanDetailedReportService.findByCondition(page, size, loanDetailedReportBean);
        	resultInfo.setData(gd.getData());
            resultInfo.setNumber(gd.getNumber());
            resultInfo.setPage(gd.getPage());
            resultInfo.setTotalPage(gd.getTotalPage());
            resultInfo.setSuccess("true");
        } catch (Exception e) {
            log.error(e.getMessage());
            resultInfo.setSuccess("false");
            resultInfo.setData(e.getMessage());
        }
        return resultInfo;
    }
}
